import Layer from '../../core/Layer';
import MultiLine from '../../base/MultiLine';
import Point from '../../core/Point';

export default class extends Layer {
    constructor(canvas, style, data = []) {
        super(canvas, style);
        this.data = data;
        this.start = style.start;
        this.end = style.end;
        this.xStep = style.xStep || this.width / (this.end - this.start) ;
        this.min = style.min || Number.MAX_VALUE;
        this.max = style.max || Number.MIN_VALUE;
    }

    getMinMax() {
        let min = Number.MAX_VALUE;
        let max = Number.MIN_VALUE;
        for (let i = this.start; i <= this.end; i++) {
            if (this.data[i] !== undefined) {
                if (min > this.data[i]) {
                    min = this.data[i];
                }
                if (max < this.data[i]) {
                    max = this.data[i];
                }
            }
        }
        this.max = max;
        this.min = min;
    }

    build() {
        this.childs.splice(0);
        let points = [];
        this.getMinMax();
        for (let i = this.start; i <= this.end; i++) {
            const data = this.data[i];
            if (data !== undefined) {
                const y = (data - this.min) / (this.max - this.min) * this.height;
                const x = i * this.xStep;
                points.push(new Point(x, y));
            }
        }
        let line = new MultiLine(this.canvas, { ...this }, points);
        this.addChild(line);
    }
}
